import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:bot_toast/bot_toast.dart';
import 'package:dear_lottery/Checker/ScanTicket/scanner_button_widgets.dart';
import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

import '../../tools/sqLite/EJ_myTicketEntity.dart';

class DL_ScanTicketVC extends StatefulWidget {
  DL_ScanTicketVC({super.key, required this.saveCallback});
  Function(int) saveCallback; //回调码：0返回键，1扫码成功返回
  @override
  State<DL_ScanTicketVC> createState() => _DL_ScanTicketVCState();
}

class _DL_ScanTicketVCState extends State<DL_ScanTicketVC>
    with WidgetsBindingObserver {
  ///保存选号到数据库
  MyTicketEntity _ticketEntity = MyTicketEntity.instan();
  //相机控制器
  final MobileScannerController controller = MobileScannerController(
    autoStart: false,
    torchEnabled: true,
    useNewCameraSelector: true,
  );
  String _scanResult = '';
  Barcode? _barcode;
  StreamSubscription<Object?>? _subscription; //相机扫描内容回调

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (!controller.value.hasCameraPermission) {
      return;
    }

    switch (state) {
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
      case AppLifecycleState.paused:
        return;
      case AppLifecycleState.resumed:
        _subscription = controller.barcodes.listen(_handleBarcode);

        unawaited(controller.start());
      case AppLifecycleState.inactive:
        unawaited(_subscription?.cancel());
        _subscription = null;
        unawaited(controller.stop());
    }
  }

  @override
  Future<void> dispose() async {
    WidgetsBinding.instance.removeObserver(this);
    unawaited(_subscription?.cancel());
    _subscription = null;
    super.dispose();
    await controller.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    _subscription = controller.barcodes.listen(_handleBarcode);

    unawaited(controller.start());
  }

  void _handleBarcode(BarcodeCapture barcodes) {
    if (mounted) {
      // setState(() {
      //   _barcode = barcodes.barcodes.firstOrNull;
      //   _scanResult = _barcode!.displayValue!;
      // });
      _barcode = barcodes.barcodes.firstOrNull;
      _scanResult = _barcode!.displayValue!;
      String res = _checkResutl(_scanResult);
      if (res.isNotEmpty) {
        _scanResult = res;
        setState(() {});

        BotToast.showWidget(toastBuilder: (context) {
          return Material(
            color: Colors.transparent,
            child: Center(
              child: Container(
                height: 180,
                width: 280,
                decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10.0))),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text(
                      'Added ticket',
                      style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: DL_Config.DL_MainColor),
                    ),
                    Text(
                      _scanResult,
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w600,
                        color: Colors.black,
                      ),
                    ),
                    // addTicketButton(),
                    SizedBox(
                      height: 40,
                      width: 230,
                      // color: Colors.yellow,
                      child: Row(children: [
                        cancelButton(),
                        Spacer(),
                        addTicketButton()
                      ]),
                    )
                  ],
                ),
              ),
            ),
          );
        });
      }
    }
  }

  _checkResutl(String inputStr) {
    // String input = 'AA 123456';

    // 定义正则表达式
    // RegExp regExp = RegExp(r'^[A-Z]{2} \d{6}$');
    // 定义正则表达式模式
    final regExp = RegExp(r'\b\d{2}[A-Z]\s\d{5}\b');

    // 判断字符串是否符合格式
    // bool isMatch = regExp.hasMatch(inputStr);

    // 在输入字符串中查找匹配
    final match = regExp.firstMatch(inputStr);

    // 如果找到匹配，返回匹配的字符串；否则返回空字符串
    // return match != null ? match.group(0) ?? '' : '';

    if (match != null) {
      var res = match.group(0);
      return res;
    } else {
      var res = '';
      return res;
    }
  }

  _addTicket() async {
    BotToast.cleanAll();

    var ticket = _scanResult.replaceAll(' ', '');
    List<String> ticketList = ticket.split('');

    if (ticketList.isEmpty) {
      BotToast.closeAllLoading();
      return;
    }
    // 获取当前时间戳（毫秒）
    int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
    var tickets = {
      "name": "Save Ticket",
      "time": currentTimeMillis,
      "numbers": jsonEncode(ticketList),
    };

    await _ticketEntity.insert(tickets);
    _goBack(1);
  }

  _cancelButton() {
    BotToast.cleanAll();
  }

  _goBack(int index) {
    widget.saveCallback(index);
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = 150;
    // double left = (MediaQuery.of(context).size.width - 300) / 2;
    double top = 200;
    return Scaffold(
      body: Stack(
        children: [
          // 扫描器
          MobileScanner(
            // onDetect: _handleBarcode,
            controller: controller,
            fit: BoxFit.contain,
            scanWindow: Rect.fromLTRB(0, top, width, height * 3), // 自定义扫描区域,
          ),

          // 镂空部分
          ClipPath(
            clipper: HollowClipper(),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
              child: Container(
                width: double.infinity,
                height: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.8), // 半透明背景
                ),
              ),
            ),
          ),
          // 其他内容
          // Center(
          //   child: Text(
          //     _barcode?.displayValue ?? 'Scan the bar code on your ticket',
          //     style: const TextStyle(fontSize: 20, color: Colors.white),
          //   ),
          // ),
          Positioned(
            top: 520,
            child: Container(
              alignment: Alignment.center,
              width: width,
              height: 30,
              child: Text(
                _scanResult.isEmpty
                    ? 'Scan the bar code on your ticket'
                    : _scanResult,
                style: const TextStyle(fontSize: 20, color: Colors.white),
              ),
            ),
          ),
          //返回按钮
          Positioned(
            top: 50,
            left: 20,
            child: IconButton(
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.white,
              ),
              onPressed: () {
                _goBack(0);
                BotToast.cleanAll();
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              alignment: Alignment.center,
              height: 100,
              color: Colors.black.withOpacity(0.4),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ToggleFlashlightButton(controller: controller),
                  // StartStopMobileScannerButton(controller: controller),
                  // Expanded(child: Center(child: _buildBarcode(_barcode))),
                  // SwitchCameraButton(controller: controller),
                  // AnalyzeImageFromGalleryButton(controller: controller),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget addTicketButton() {
    double btnH = 36.0;
    double btnW = 100.0;
    return Container(
      height: btnH,
      width: btnW,
      decoration: BoxDecoration(
          color: DL_Config.DL_MainColor,
          borderRadius: BorderRadius.all(Radius.circular(btnH * 0.5))),
      child: TextButton(
          onPressed: () {
            debugPrint('Scan Ticket');
            _addTicket();
          },
          child: const Text(
            'OK',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          )),
    );
  }

  Widget cancelButton() {
    double btnH = 36.0;
    double btnW = 100.0;
    return Container(
      height: btnH,
      width: btnW,
      decoration: BoxDecoration(
          //灰色
          color: const Color.fromARGB(255, 184, 183, 183),
          borderRadius: BorderRadius.all(Radius.circular(btnH * 0.5))),
      child: TextButton(
          onPressed: () {
            debugPrint('Cancel');
            _cancelButton();
          },
          child: const Text(
            'Cancel',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          )),
    );
  }
}

class HollowClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();

    // 创建一个矩形
    path.addRect(Rect.fromLTRB(0, 0, size.width, size.height));

    // 创建一个镂空区域
    double width = 300;
    double left = (size.width - 300) / 2;
    double top = 200;
    path.addRect(Rect.fromLTWH(left, top, width, width)); // 镂空区域与背景相同大小

    // 使用差集来实现镂空效果
    path.fillType = PathFillType.evenOdd; // 使用奇偶规则
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
